/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import React, { useCallback, useState, useMemo, useEffect } from 'react';
import PageHeaderLayout from '@/layouts/PageHeaderLayout';
import { connect, useSelector } from 'dva';
import { Form, Row, Col, Button, Select, Modal, message, Icon } from 'antd';
import { isEqual } from 'lodash';
import AddressCascader from '@/components/AddressCascader';
import moment from 'moment/moment';
import KbRangePicker from '@/components/KbRangePicker';
import StandardTable from '@/components/StandardTable';
import { Yzs, Brands } from '@/components/Select';
import { PhotoSlider } from 'react-photo-view';
import DispatchPianqu from '@/components/_pages/Post/Area/DispatchPianqu';
import { getLStorage } from '@/utils/utils';
import styles from './style.less';
import 'react-photo-view/dist/index.css';

const FormItem = Form.Item;
const { Option } = Select;

const formItemLayout = {
  labelCol: {
    xs: { span: 24 },
    sm: { span: 4 },
  },
  wrapperCol: {
    xs: { span: 24 },
    sm: { span: 20 },
  },
};

const formTailLayout = {
  labelCol: {
    xs: { span: 24 },
    sm: { span: 4 },
  },
  wrapperCol: {
    xs: { span: 24 },
    sm: { span: 8, offset: 4 },
  },
};

const timeRange = [
  moment()
    .startOf('day')
    .subtract(30, 'days'),
  moment()
    .startOf('day')
    .subtract(0, 'days'),
];

const formator = 'YYYY-MM-DD';

const inventory_status_map = {
  all: '全部状态',
  1: '待出库',
  2: '已出库',
  3: '已退回',
};
const upload_status_map = {
  all: '全部状态',
  1: '未上传',
  2: '上传中',
  4: '上传成功',
  5: '上传失败',
};

function ImageView({ src }) {
  const [visible, setVisible] = React.useState(false);
  const [photoIndex, setPhotoIndex] = React.useState(0);
  return (
    <div>
      <a onClick={() => setVisible(true)}>查看底单</a>
      <PhotoSlider
        images={src.map(item => ({ src: item }))}
        visible={visible}
        onClose={() => setVisible(false)}
        index={photoIndex}
        onIndexChange={setPhotoIndex}
      />
    </div>
  );
}

const InventoryManagement = Form.create()(
  ({ form, dispatch, loading, userInfo, options: { key } }) => {
    const { getFieldDecorator, validateFields, setFieldsValue, getFieldValue } = form;
    const { branchId, branchLevel, branch = [] } = userInfo;
    // 开启开启驿站片区管理
    const { inn_area_ids, phone, area_ids } = useSelector(({ user }) => user.currentUser.user_info);
    const isZyAccount = key == 'post';
    const isYz = key === 'yz';

    const cacheAreaId = getLStorage(`KB_INN_AREA_${phone}`);
    const isCompany = area_ids == '*';
    // 防止片区被关闭，导致请求带上上一个的片区ID
    const initAreaId = inn_area_ids.includes(cacheAreaId)
      ? cacheAreaId
      : isCompany
        ? '0'
        : inn_area_ids.join(',');

    const [brandMap, setBrandMap] = useState({});
    const [tableList, setTableList] = useState({ list: [], pagination: {} });
    const [visible, setVisible] = useState(false);
    const [formData, setFormData] = useState({});
    const [reqYzPayload, setReqYzPayload] = useState({ branchId, area_id: initAreaId });
    const [branchInfo, setBranchInfo] = useState({
      branchId: branch.filter(val => (isZyAccount ? val.level != 0 : val)).map(i => i.id),
      branch,
    });

    useEffect(
      () => {
        dispatch({
          type: 'global/getBrandList',
        }).then((brands = []) => {
          const obj = {};
          brands.forEach(({ brand, brand_en }) => {
            obj[brand_en] = brand;
          });
          setBrandMap(obj);
        });
      },
      [dispatch],
    );

    useEffect(
      () => {
        if (branchLevel == 0 && isZyAccount) {
          setBranchInfo({
            branch: [
              {
                id: '0',
                name: '中国邮政集团有限公司',
                level: '0',
                pid: '-2', // 自定义pid用来区分是否是单独属于总公司账号
              },
            ],
            branchId: ['0'],
          });
        }
      },
      [isZyAccount, branchLevel],
    );

    const getFormValues = useCallback(
      (then = () => {}) => {
        validateFields((err, value) => {
          if (err) return;
          const formValues = { ...value };
          const [startTime, endTime] = value.time;
          delete formValues.time;

          if (value.branch_id) {
            delete formValues.branch_id;
          }

          if (value.storage_type == 'all') {
            formValues.storage_type = '';
          }
          if (value.upload_status == 'all') {
            formValues.upload_status = '';
          }

          formValues.start_date = startTime.format(formator);
          formValues.end_date = endTime.format(formator);

          const cachedAreaId = getLStorage(`KB_INN_AREA_${phone}`);
          // 防止片区被关闭，导致请求带上上一个的片区ID
          const area_id = inn_area_ids.includes(cachedAreaId)
            ? cachedAreaId
            : isCompany
              ? '0'
              : inn_area_ids.join(',');

          formValues.area_id = area_id;

          setFormData(prevState => ({
            ...formValues,
            ...prevState,
          }));
          then(formValues);
        });
      },
      [validateFields, inn_area_ids, isCompany],
    );

    const getList = useCallback(
      p => {
        getFormValues(payload => {
          if (!payload.cm_id) {
            message.error('请先选择具体驿站站点再查询！');
            return;
          }
          dispatch({
            type: 'inventory/getList',
            payload: {
              ...payload,
              page: p,
              page_size: 20,
            },
          }).then(res => {
            setTableList(res);
          });
        });
      },
      [getFormValues, dispatch, isYz],
    );

    const onSubmit = useCallback(
      e => {
        e.preventDefault();
        getList(1);
      },
      [getList],
    );

    const onTableChange = useCallback(
      ({ current }) => {
        getList(current);
      },
      [getList],
    );

    const onYzSelect = useCallback((_, option = {}) => {
      const { props = {} } = option;
      const { name } = props;

      setFormData(prevState => ({
        ...prevState,
        cm_name: name,
      }));
    }, []);

    const onBrandSelect = useCallback((_, option = {}) => {
      const { props = {} } = option;
      const { name } = props;

      setFormData(prevState => ({
        ...prevState,
        brand_name: name,
      }));
    }, []);

    const onAddressSelect = useCallback(
      (value, option = []) => {
        setFieldsValue({
          cm_id: undefined,
        });
        const branch_id = [...value].pop();
        const _reqYzPayload = { branch_id };
        if (isEqual(value, branchId)) return;
        setReqYzPayload(_reqYzPayload);
        if (isZyAccount) {
          const address_name = option.map(v => v.name).join('');
          setFormData(prevState => ({
            ...prevState,
            address_name,
          }));
        }
      },
      [setFieldsValue, branchId, isZyAccount],
    );

    // const onExport = useCallback(
    //   () => {
    //     getFormValues(() => {
    //       setVisible(true);
    //     });
    //   },
    //   [getFormValues],
    // );

    const onOK = useCallback(
      () => {
        dispatch({
          type: 'inventory/createExport',
          payload: formData,
        })
          .then(() => {
            Modal.info({
              title: '温馨提示',
              content: '导出数据申请已提交，请至【报表下载】处下载',
            });
            setVisible(false);
          })
          .catch(err => {
            Modal.info({
              title: '温馨提示',
              content: err,
            });
            setVisible(false);
          });
      },
      [dispatch, formData],
    );

    const columns = useMemo(
      () => [
        {
          title: '单号/品牌',
          dataIndex: 'waybill_no',
          key: 'waybill_no',
          align: 'center',
          width: 200,
          render: (_, { brand, waybill_no }) => (
            <Row>
              <Col>{waybill_no}</Col>
              <Col>{brandMap[brand] || ''}</Col>
            </Row>
          ),
        },
        {
          title: '收件人',
          dataIndex: 'user_name',
          key: 'user_name',
          align: 'center',
          width: 200,
          render: (_, { user_name, express_phone }) => (
            <Row>
              <Col>{express_phone}</Col>
              <Col>{user_name}</Col>
            </Row>
          ),
        },
        {
          title: '库存/上传状态',
          dataIndex: 'status',
          key: 'status',
          align: 'center',
          width: 200,
          render: (_, { status_cn, upload_state, upload_state_cn }) => (
            <Row>
              <Col>{status_cn || '--'}</Col>
              <Col>
                <Icon type="cloud-upload" style={{ marginRight: 10 }} />
                <span style={{ color: upload_state == '1' ? 'red' : '' }}>
                  {upload_state_cn || '--'}
                </span>
              </Col>
            </Row>
          ),
        },
        {
          title: '通知状态',
          dataIndex: 'sms_state',
          key: 'sms_state',
          align: 'center',
          width: 200,
          render: (_, { sms_state_cn, ivr_state_cn }) => (
            <Row>
              <Col>
                {sms_state_cn ? (
                  <span>
                    <Icon type="mail" theme="filled" style={{ marginRight: 10 }} />
                    {sms_state_cn}
                  </span>
                ) : (
                  ''
                )}
              </Col>
              <Col>
                {ivr_state_cn ? (
                  <span>
                    <Icon type="phone" theme="filled" style={{ marginRight: 10 }} />
                    {ivr_state_cn}
                  </span>
                ) : (
                  ''
                )}
              </Col>
            </Row>
          ),
        },
        {
          title: '取件码',
          dataIndex: 'pickup_code',
          key: 'pickup_code',
          align: 'center',
          width: 200,
        },
        {
          title: '入库时间',
          dataIndex: 'storage_time',
          key: 'storage_time',
          align: 'center',
          width: 200,
          render: (storage_time, { storage_img_url = [] }) => (
            <Row type="flex" style={{ width: '100%' }} justify="center">
              <Col>{storage_time}</Col>
              <Col>{storage_img_url.length > 0 && <ImageView src={storage_img_url} />}</Col>
            </Row>
          ),
        },
        {
          title: '出库/退回时间',
          dataIndex: 'check_out_time',
          key: 'check_out_time',
          align: 'center',
          width: 200,
          render: (_, { status, back_time, out_time, out_img_url = [] }) => {
            const timeType = {
              2: out_time,
              3: back_time,
            };
            return (
              <Row type="flex" style={{ width: '100%' }} justify="center">
                <Col>{timeType[status] || '--'}</Col>
                <Col>{out_img_url.length > 0 && <ImageView src={out_img_url} />}</Col>
              </Row>
            );
          },
        },
      ],
      [brandMap],
    );

    const onChangePianqu = area_id => {
      getList(1);
      setReqYzPayload(prevData => ({
        ...prevData,
        area_id,
      }));
    };

    return (
      <PageHeaderLayout
        title={
          <Row type="flex" justify="space-between">
            <Col>库存记录</Col>
            <Col>
              <DispatchPianqu type="inn" onChange={onChangePianqu} />
            </Col>
          </Row>
        }
      >
        <div className={styles.main}>
          <Form onSubmit={onSubmit} style={{ marginBottom: 24 }}>
            <Row type="flex">
              <Col xs={24} sm={24} lg={24} xl={12} xxl={8}>
                <FormItem label="入库时间" {...formItemLayout}>
                  {getFieldDecorator('time', {
                    initialValue: timeRange,
                    rules: [
                      {
                        required: true,
                        message: '请选择入库时间',
                      },
                    ],
                  })(
                    <KbRangePicker
                      style={{ width: '100%' }}
                      allowClear={false}
                      max={3}
                      showTime={false}
                      format={formator}
                    />,
                  )}
                </FormItem>
              </Col>
              {isZyAccount && (
                <Col xs={24} sm={24} lg={24} xl={12} xxl={8}>
                  <FormItem label="所属区域" {...formItemLayout}>
                    {getFieldDecorator('branch_id', {
                      initialValue: branchInfo.branchId,
                      rules: [
                        {
                          required: true,
                          message: '请选择所属区域',
                        },
                      ],
                    })(
                      <AddressCascader
                        request
                        changeOnSelect
                        canChooseParent={false}
                        width="100%"
                        branch={branchInfo.branch}
                        onSelect={onAddressSelect}
                      />,
                    )}
                  </FormItem>
                </Col>
              )}
              <Col xs={24} sm={24} lg={24} xl={12} xxl={8}>
                <FormItem label="驿站站点" {...formItemLayout}>
                  {getFieldDecorator('cm_id', {
                    rules: [
                      {
                        required: true,
                        message: '请选择驿站站点',
                      },
                    ],
                  })(
                    <Yzs
                      style={{ width: '100%' }}
                      showAll={false}
                      onSelect={onYzSelect}
                      reqPayload={reqYzPayload}
                      repeatRequest
                      placeholder="请选择具体驿站"
                    />,
                  )}
                </FormItem>
              </Col>
              <Col xs={24} sm={24} lg={24} xl={12} xxl={8}>
                <FormItem label="快递品牌" {...formItemLayout}>
                  {getFieldDecorator('brand', {
                    initialValue: 'all',
                  })(<Brands style={{ width: '100%' }} onSelect={onBrandSelect} />)}
                </FormItem>
              </Col>
              <Col xs={24} sm={24} lg={24} xl={12} xxl={8}>
                <FormItem label="库存状态" {...formItemLayout}>
                  {getFieldDecorator('storage_type', {
                    initialValue: 'all',
                  })(
                    <Select style={{ width: '100%' }}>
                      {Object.keys(inventory_status_map)
                        .reverse()
                        .map(val => (
                          <Option key={val} value={val}>
                            {inventory_status_map[val]}
                          </Option>
                        ))}
                    </Select>,
                  )}
                </FormItem>
              </Col>

              <Col xs={24} sm={24} lg={24} xl={12} xxl={8}>
                <FormItem label="上传状态" {...formItemLayout}>
                  {getFieldDecorator('upload_status', {
                    initialValue: 'all',
                  })(
                    <Select style={{ width: '100%' }}>
                      {Object.keys(upload_status_map)
                        .reverse()
                        .map(val => (
                          <Option key={val} value={val}>
                            {upload_status_map[val]}
                          </Option>
                        ))}
                    </Select>,
                  )}
                </FormItem>
              </Col>
              <Col xs={24} sm={24} lg={24} xl={12} xxl={8}>
                <FormItem {...formTailLayout}>
                  <Button type="primary" htmlType="submit" disabled={!getFieldValue('cm_id')}>
                    查询
                  </Button>
                </FormItem>
              </Col>
            </Row>
            {/* <FormItem>
              <Button type="primary" onClick={onExport}>
                导出
              </Button>
            </FormItem> */}
          </Form>
          <StandardTable
            rowKey="id"
            loading={loading}
            data={tableList}
            columns={columns}
            scroll={{ x: 800 }}
            onChange={onTableChange}
          />
          <Modal
            title="温馨提示：确定导出如下数据？"
            visible={visible}
            onCancel={() => setVisible(false)}
            onOk={onOK}
            centered
          >
            <Row gutter={[20, 20]}>
              <Col>
                入库时间：
                {formData.start_date} ~ {formData.end_date}
              </Col>
              <Col>
                驿站站点：
                {formData.cm_name || '全部驿站'}
              </Col>
              <Col span={24}>
                <Row type="flex">
                  {isZyAccount && (
                    <Col span={12}>
                      <span>所属区域：</span>
                      <span>
                        {formData.address_name ||
                          branch
                            .filter(v => v.level > 0)
                            .map(v => v.name)
                            .join('')}
                      </span>
                    </Col>
                  )}
                  <Col span={12}>
                    快递品牌：
                    {formData.brand_name || '全部品牌'}
                  </Col>
                </Row>
              </Col>
              <Col span={24}>
                <Row type="flex">
                  <Col span={12}>
                    库存状态：
                    {inventory_status_map[formData.storage_type] || '全部状态'}
                  </Col>
                  <Col span={12}>
                    上传状态：
                    {upload_status_map[formData.upload_status] || '全部状态'}
                  </Col>
                </Row>
              </Col>
            </Row>
          </Modal>
        </div>
      </PageHeaderLayout>
    );
  },
);

export default connect(({ setting, user, loading }) => ({
  userInfo: user.currentUser.user_info,
  loading: loading.effects['inventory/getList'],
  ...setting,
}))(React.memo(InventoryManagement));
